package com.ztom.beans.factory.support.lifecycle

import cn.hutool.core.util.ClassUtil
import com.ztom.beans.exception.BeansException
import com.ztom.beans.factory.support.pojo.BeanDefinition

/**
 * @author ZhangTao
 */
class DisposableBeanAdapter(
    val bean: Any,
    val beanName: String,
    val beanDefinition: BeanDefinition
) : DisposableBean {

    override fun destroy() {
        // 1.实现了 DisposableBean 接口
        if (bean is DisposableBean) {
            bean.destroy()
        }
        // 原型 bean 不支持自定义销毁方法
        if (beanDefinition.isPrototype()) {
            return
        }
        val destroyMethodName = beanDefinition.destroyMethodName
        // 2.自定义了 destroy 方法, 考虑有同时继承 DisposableBean 接口且自定义同名方法 destroy
        if (!destroyMethodName.isNullOrBlank() && (bean !is DisposableBean || destroyMethodName != "destroy")) {
            val destroyMethod = ClassUtil.getPublicMethod(bean::class.java, destroyMethodName)
                ?: throw BeansException("Cannot find a destroy method named '$destroyMethodName' on bean with name '$beanName'")
            destroyMethod.invoke(bean)
        }

    }
}